package com.cenxi.common.exceptions;

import com.cenxi.common.result.Resp;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理器
 *  * @author admin
 */
@Slf4j
@ControllerAdvice
@ResponseBody
public class GlobalHandlerException extends RuntimeException {

    /**
     * 处理鉴权异常异常
     */
    @ExceptionHandler(value = MalformedJwtException.class)
    public Resp tokenVerifyException(MalformedJwtException e, HttpServletRequest request) {
        log.error("鉴权异常！ msg: -> {}, url - >{}", e.getMessage(), request.getRequestURI());
        return Resp.error("鉴权异常", "0002");
    }

    /**
     * 处理token过期异常
     */
    @ExceptionHandler(value = ExpiredJwtException.class)
    public Resp tokenVerifyException(ExpiredJwtException e, HttpServletRequest request) {
        log.error("token过期！ msg: -> {}, url - >{}", e.getMessage(), request.getRequestURI());
        return Resp.error("token过期", "0002");
    }

    /**
     * 处理自定义的业务异常
     */
    @ExceptionHandler(value = ServiceException.class)
    public Resp serviceException(ServiceException e, HttpServletRequest request) {
        log.error("业务异常 msg: -> {}, url - >{}", e.getMessage(), request.getRequestURI());
        return Resp.error(e.getMessage(), "0002");
    }
    /**
     * 处理空指针的异常
     */
    @ExceptionHandler(value = NullPointerException.class)
    public Resp exceptionHandler(NullPointerException e, HttpServletRequest request) {
        log.error("空指针异常 msg: -> {}, url - >{}", e, request.getRequestURI());
        return Resp.error("空指针异常", "0002");
    }

    /**
     * 服务器异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Resp exception(Exception e, HttpServletRequest request) {
        log.error("服务器异常 msg: -> {}, url - >{}", e, request.getRequestURI());
        return Resp.error("服务器异常", "500");
    }

    /**
     * Assert异常
     */
    @ExceptionHandler(value = IllegalArgumentException.class)
    public Resp exceptionHandler(IllegalArgumentException e, HttpServletRequest request) {
        log.error("Assert异常 msg: -> {}, url - >{}", e.getMessage(), request.getRequestURI());
        return Resp.error(e.getMessage(), "0002");
    }
}
